package com.zy.explore.design.patterns.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略模式具体使用 服务类
 *
 * @author ZY
 * @date 2021/11/02
 */
@Component
public class StrategyUseService implements ApplicationContextAware {

    /**
     * 缓存所有策略类型和对应处理类的map
     */
    private final Map<StrategyTypeEnum, IStrategy> strategyMap = new ConcurrentHashMap<>();

    public void doSomething(StrategyTypeEnum typeEnum, Object params) {
        IStrategy strategy = strategyMap.get(typeEnum);
        if (strategy != null) {
            strategy.doSomething(params);
        }
    }

    /**
     * 设置应用程序上下文
     *
     * @param applicationContext 应用程序上下文
     * @throws BeansException Bean异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IStrategy> tempMap = applicationContext.getBeansOfType(IStrategy.class);
        tempMap.values().forEach(strategyService -> strategyMap.put(strategyService.getType(), strategyService));
    }
}
